# debate_controller_backup.py
from agents import Host, Judge, Debater, HumanDebater
from debate_recorder import DebateRecorder
import json
from debater_prompt import DebaterPrompt
from llm_integration import LLMIntegration
from debate_agents.basic_dabate_agent import BasicDebateAgent
from debate_agents.rag_debate_agent import RAGDebateAgent
from customize.get_ollama import GetOllama
from my_tools.debate_evidence_retriever import DebateEvidenceTool
class DebateFlow:
    def __init__(self, flow_file):
        with open(flow_file, 'r', encoding='utf-8') as f:
            self.flow = json.load(f)

    def get_flow_stages(self):
        return self.flow.get('stages', [])


class DebateController:
    def __init__(self, topic, debate_model="ai_vs_ai", human_size="正方", agent_type="basic"):
        self.prompt_manager = None
        self.agent_type = agent_type
        self.recorder = DebateRecorder()
        # self.llm_integration = LLMIntegration(url="127.0.0.1:11434", type="normal", title="knowledge_base")
        self.deepseek = GetOllama(model_name="qwen3:1.7b", model_type=1)()
        self.qwen = GetOllama(model_name="qwen2.5:3b", model_type=1)()
        if self.agent_type == "basic":
            self.debate_agent = BasicDebateAgent(llm=self.deepseek)
        else:
            self.debate_agent = RAGDebateAgent(llm=self.deepseek, evidence_tool=DebateEvidenceTool(llm=self.qwen))
        self.host = Host("主持人", self.recorder)
        self.judge = Judge("裁判员", self.recorder, llm=self.deepseek)
        self.topic = topic
        self.human_size = human_size
        self.debate_model = debate_model
        self.debaters = []
        self.chn_num = ["一", "二", "三", "四"]
        self._create_debaters()
        self._set_debater_prompt()
        self.debate_flow = DebateFlow("debate_flow.json")
        self.current_human_debater = None

    def _set_debater_prompt(self):
        self.prompt_manager = DebaterPrompt("debater_prompts.json")
        # 给辩手赋值提示词
        for debater in self.debaters:
            prompt = self.prompt_manager.get_prompt(debater.side, debater.name)
            if prompt:
                debater.prompt = prompt

    def _create_debaters(self):
        for num in self.chn_num:
            if self.debate_model == "ai_vs_ai":
                self.debaters.append(Debater(f"{num}辩", "正方", position=f"{num}辩", recorder=self.recorder,
                                             topic=self.topic, llm=self.debate_agent))
                self.debaters.append(Debater(f"{num}辩", "反方", position=f"{num}辩", recorder=self.recorder,
                                             topic=self.topic, llm=self.debate_agent))
            else:
                if self.human_size == "正方":
                    self.debaters.append(HumanDebater(f"{num}辩", "正方", position=f"{num}辩",
                                                      recorder=self.recorder))
                    self.debaters.append(Debater(f"{num}辩", "反方", position=f"{num}辩", recorder=self.recorder,
                                                 topic=self.topic, llm=self.debate_agent))
                else:
                    self.debaters.append(Debater(f"{num}辩", "正方", position=f"{num}辩", recorder=self.recorder,
                                                 topic=self.topic, llm=self.debate_agent))
                    self.debaters.append(HumanDebater(f"{num}辩", "反方", position=f"{num}辩",
                                                      recorder=self.recorder))

    def get_debates_info(self):
        con_size = []
        pro_size = []
        for debater in self.debaters:
            if debater.side == "正方":
                pro_size.append([debater.side + debater.name, "蓄势代发"])
            else:
                con_size.append([debater.side + debater.name, "蓄势代发"])
        return [pro_size, con_size]

    def human_response(self, message):
        """接收人类辩手的发言"""
        if self.current_human_debater:
            self.current_human_debater.add_record(message)

    def run_debate(self):
        """运行辩论赛流程"""
        # 开始阶段
        yield self.host.name, self.host.start_debate(topic=self.topic)

        # 辩论阶段
        stages = self.debate_flow.get_flow_stages()
        for stage in stages:
            stage_name = stage.get('name')
            yield self.host.name, self.host.control_stage(stage_name)
            actions = stage.get('actions', [])
            for action in actions:
                side = action.get('side')
                position = action.get('position')
                action_type = action.get('action_type')
                for debater in self.debaters:
                    if debater.side == side and debater.position == position:
                        if self.debate_model == "ai_vs_human" and side == self.human_size:
                            self.current_human_debater = debater
                            # 人类辩手环节，返回特殊标识等待输入
                            self.current_human_debater.stage = stage_name
                            self.current_human_debater.action_type = action_type
                            yield debater.side + debater.name, "human_turn"
                        else:
                            # AI辩手正常发言
                            yield debater.side + debater.name, debater.debate(stage_name, action_type)
                        break

        # 评审阶段
        yield self.host.name, self.host.statr_judge()
        yield self.judge.name, self.judge.summarize()
        yield self.host.name, self.host.end_debate()


if __name__ == '__main__':
    # 初始化控制器
    controller = DebateController("中学生是否应该带手机进入校园")

    # 运行辩论流程并打印输出
    print("===== 辩论开始 =====")
    for speaker, content in controller.run_debate():
        print(f"[{speaker}] {content}")
        print("-" * 50)
    print("===== 辩论结束 =====")